home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: C unions
- Date: 6 Mar 1996 01:48:27 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4hjn1bINN5bb@keats.ugrad.cs.ubc.ca>
- References: <367cc$0359.14a@news.express.ca>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <367cc$0359.14a@news.express.ca>,
- Gary Chan <gchan@express.ca> wrote:
- >I need a C union that allows me to freely interpret an integer
- >separately as the least significant byte or the most significant byte,
- >and as a single integer.
- >
- >Can someone help me get started on this?
-
- Sorry, you can't do that, unless you can depend on implementation-defined
- behavior of unions.
-
- It is illegal to access the value of a union member through a different union
- member.
-
- At the very best, your attempt will result in code that depends on the byte
- ordering of the implementation. Furthmore, structure packing and alignment will
- play a role as well, as will the integer size! You are assuming that it is 16
- bits, correct?
-
- The proper way to access the lower eight bits of the integer is to bitwise AND
- it with 0xff to mask out all bits except the lower eight. That portably gives
- you the least significant eight bits. To get the next set of eight bits from
- the integer, you shift it right by eight, and do the same AND. That gets you
- your high order byte of a 16-bit integer:
-
- #define HILO(N,H,L) ((H) = (N) >> 8 & 0xff, (L) = (N) & 0xff)
-
- This macro splits the quantity N (assumed to be 0-65535) into a high-order and
- low-order byte values stored in the lvalues represented by H and L.
- --
-
-